import json
import os
from PyQt5.QtWidgets import (
    QWidget,
    QGridLayout,
    QGroupBox,
    QTabWidget,
    QHBoxLayout,
    QVBoxLayout,
    QLabel,
    QStyledItemDelegate,
    QDesktopWidget,
    QPushButton,
    QFileDialog,
    QComboBox,
    QFrame,
    QScrollArea,
    QAbstractItemView,
    QTableWidgetItem,
    QTableWidget,
    QSpacerItem,
    QSizePolicy,
    QLineEdit,
    QGraphicsOpacityEffect,
)
from PyQt5.QtCore import pyqtSignal, pyqtSlot, Qt, QObject, QEvent
from PyQt5.QtGui import QPainter, QPen, QColor, QDoubleValidator, QPixmap, QIcon, QBrush
from functools import partial
from pydantic import BaseModel, Field, field_validator
import gui.controls.envs as envs

# import gui.controls.envs as envs
from ..dlg_mulit_instance import DlgMutliInstance
from ..custom_table import CustomTable
from ..dlg_params import DlgParams
from ..util.file_operation import FileOperation
from ..util.excel_formula import ExcelFormula
from ..util.type_conversion import TypeConversion
from ..custom_widget import LineEditFloat, LineEditStr, LineEditInt, SelectBox
from ..util import data_clear as DC
from enum import Enum


class DlgBaseInfo(DlgMutliInstance):
    baseInfo_save_signal = pyqtSignal(object)

    def __init__(self, parent=None):
        super(DlgBaseInfo, self).__init__(parent)

        self.setWindowTitle("基本信息")
        self.setMinimumWidth(500)

        # 创建垂直布局
        layout = QVBoxLayout(self)
        self.widgetDict = {}
        self.labelDict = {}

        contentWidget = self.createContentWidget()
        layout.addWidget(contentWidget)

        btnLayout = QHBoxLayout()
        btnLayout.setAlignment(Qt.AlignCenter)  # 设置居中对齐
        pBtnCancel = QPushButton("取消")
        pBtnCancel.setObjectName("pBtnCancel")
        pBtnCancel.clicked.connect(self.close)
        self.pBtnOK = QPushButton("保存")
        self.pBtnOK.setObjectName("pBtnOK")
        self.pBtnOK.clicked.connect(self.on_pBtnOK_clicked)
        btnLayout.addWidget(self.pBtnOK)
        btnLayout.addWidget(pBtnCancel)

        self.pBtnOK.setFocusPolicy(Qt.NoFocus)
        pBtnCancel.setFocusPolicy(Qt.NoFocus)

        layout.addLayout(btnLayout)
        self.setLayout(layout)

        self.setDefaultValues()

        # self.cacheFile = "data/ipimas/uis/baseInfo.json"
        # data = FileOperation.read_json(self.cacheFile)
        # self.loadData(data)

    # def init(
    #     self, data={}, select1Title="", select2Title="123", select1Opt=[], select2Opt=[]
    # ):
    def init(
        self,
        data={},
        select1Title="",
        select2Title="",
        analysisAreaOpt=[],
        failureTypesOpt=[],
    ):
        self.widgetDict["analysisArea"].updateItem(analysisAreaOpt)
        self.widgetDict["failureTypes"].updateItem(failureTypesOpt)
        if select1Title:
            self.labelDict["analysisArea"].setText(select1Title)
        if select2Title:
            self.labelDict["failureTypes"].setText(select2Title)

        self.loadData(data)

    def createContentWidget(self):

        paramsList = [
            {
                "name": "analysisArea",
                "type": "select",
                "title": "分析区域",
                "options": [],
            },
            {
                "name": "failureTypes",
                "type": "select",
                "title": "失效类型",
                "options": [],
            },
        ]

        widget = QWidget()
        gridLayout = QGridLayout()
        widget.setLayout(gridLayout)
        self.createParameterUI(paramsList, gridLayout)
        return widget

    def setDefaultValues(self):
        pass

    def createParameterUI(self, list, layout):
        for index, item in enumerate(list):
            label = QLabel(item["title"])
            self.labelDict[item["name"]] = label
            layout.addWidget(label, index, 0)

            if item["type"] == "str":
                self.widgetDict[item["name"]] = LineEditStr()
            if item["type"] == "int":
                self.widgetDict[item["name"]] = LineEditInt()
            elif item["type"] == "float":
                self.widgetDict[item["name"]] = LineEditFloat()
            elif item["type"] == "select":
                self.widgetDict[item["name"]] = SelectBox(
                    options=item["options"], onChanged=item.get("onChanged")
                )
            layout.addWidget(self.widgetDict[item["name"]], index, 1)

    def on_pBtnOK_clicked(self):
        data = {}
        for key, widget in self.widgetDict.items():
            data[key] = widget.getValue()
        # FileOperation.write_json(self.cacheFile, data)
        self.close()
        self.baseInfo_save_signal.emit(data)

    def loadData(self, data):
        if data:
            for widget, value in data.items():
                if widget in self.widgetDict:
                    self.widgetDict[widget].setValue(value)
